package com.lp.multi.thread.example04;

/**
 * @author: lp
 * @create: 2021-06-21 9:31
 * @description: 模拟龟兔赛跑
 */
public class Race implements Runnable{

    private static String winner = null;

    @Override
    public void run() {
        String threadName = Thread.currentThread().getName();
        for (int i = 1; i <= 1000;i=i+getSteps(threadName)) {
            boolean isGameOver = gameOver(i);
            if(isGameOver){
                break;
            }
            System.out.println(threadName+"-->跑了"+i+"步");
            if(threadName.equals("兔子") && i > 500){
                try {
                    System.out.println("兔子跑了一半，睡会儿,时间:"+System.currentTimeMillis());
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

           i=threadName.equals("兔子") ? i+10 : i++;
        }
    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();

    }

    private int getSteps(String threadName){
        if(threadName.equals("兔子")){
            return 10 ;
        }else{
            return 1;
        }
    }

    private boolean gameOver(int steps){
        if(winner != null){
            return true;
        }
        if(steps >=1000){
            winner = Thread.currentThread().getName();
            System.out.println("the winner is" + winner);
            return true;
        }
        return false;
    }
}
